/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package azhar.database;

import java.sql.Statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author Al-Insan
 */
public class DatabaseConnectivity {

    private Connection connect;
    private ResultSet result;
    private PreparedStatement state;

    public DatabaseConnectivity() {
        createConnection("jdbc:mysql://localhost:3306", "root", "");
    }

    public DatabaseConnectivity(String dbName) {
        createConnection("jdbc:mysql://localhost:3306/" + dbName, "root", "root");
    }

    public DatabaseConnectivity(String dbName, String user) {
        createConnection("jdbc:mysql://localhost:3306/" + dbName, user, "");
    }

    public DatabaseConnectivity(String dbName, String user, String pass) {
        createConnection("jdbc:mysql://localhost:3306/" + dbName, user, pass);
    }

    private void createConnection(String url, String user, String pass) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection(url, user, pass);
            connect.setAutoCommit(true);
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Fatal Error: " + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }

    public Connection getConnect() {
        return connect;
    }

    public void setConnect(Connection connect) {
        this.connect = connect;
    }

    public ResultSet getResult() {
        return result;
    }

    public void setResult(ResultSet result) {
        this.result = result;
    }

    public PreparedStatement getState() {
        return state;
    }

    public void setState(PreparedStatement state) {
        this.state = state;
    }

    public void manipulateQuery(String statement) {
        try {
            Statement stat = connect.createStatement();
            stat.execute(statement);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Fatal Error: " + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void executeQuery(String query) {
        try {
            Statement stat = connect.createStatement();
            result = stat.executeQuery(query);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Fatal Error: " + ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
        }
    }

    public ArrayList getData(String colName) throws SQLException {
        ArrayList data = new ArrayList();
        while (result.next()) {
            data.add(result.getString("Database"));
        }
        return data;
    }

    public void closeConnection() throws SQLException {
        connect.close();
    }
}
